package me.helllp.book.concurrent.ch04;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * AtomicIntegerFieldUpdater的使用方法
 * 
 * @author Administrator
 *
 */
public class AtomicIntegerFieldUpdaterDemo {
	public static class Candidate{
		int id;
		//	不能是private的，必须使用volatile进行定义，不支持static
		volatile int score;
	}
	
	public final static AtomicIntegerFieldUpdater<Candidate> scoreUpdater
		= AtomicIntegerFieldUpdater.newUpdater(Candidate.class, "score");
	
	//	用来验证结果的准确性
	public static AtomicInteger allScore = new AtomicInteger(0);
	
	public static Integer normalInteger = 0;
	
	public static void main(String[] args) throws InterruptedException {
		final Candidate std = new Candidate();
		Thread[] t = new Thread[10000];
		
		for(int i=0; i<t.length; i++){
			t[i] = new Thread(new Runnable() {
				public void run() {
					if(Math.random() > 0.4){
						normalInteger +=1;
						scoreUpdater.incrementAndGet(std);
						allScore.incrementAndGet();
					}
				}
			});
			t[i].start();
		}
		
		for(int i=0; i<t.length; i++){
			t[i].join();
		}
		
		System.out.println("未同步的结果：" + normalInteger);
		System.out.println("score = " + std.score);
		System.out.println("allScore = " + allScore);
	}
}
